package org.example.system.config;

import cn.hutool.captcha.generator.CodeGenerator;
import cn.hutool.captcha.generator.MathGenerator;
import cn.hutool.captcha.generator.RandomGenerator;
import org.example.system.plugin.captcha.CaptchaProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

import java.awt.*;

import lombok.RequiredArgsConstructor;

/**
 * 验证码自动装配配置
 * 配置验证码生成器和字体
 *
 * @author LY
 */
@Configuration
@RequiredArgsConstructor
public class CaptchaConfig {

    private static final String MATH_TYPE = "math";
    private static final String RANDOM_TYPE = "random";
    private static final int DEFAULT_FONT_WEIGHT = Font.PLAIN;

    private final CaptchaProperties captchaProperties;

    /**
     * 验证码文字生成器
     *
     * @return CodeGenerator
     * @throws IllegalArgumentException 如果验证码类型无效
     */
    @Bean
    public CodeGenerator codeGenerator() {
        if (captchaProperties == null || captchaProperties.getCode() == null) {
            throw new IllegalArgumentException("Captcha code properties must not be null");
        }

        String codeType = captchaProperties.getCode().getType();
        int codeLength = captchaProperties.getCode().getLength();

        if (!StringUtils.hasText(codeType)) {
            throw new IllegalArgumentException("Captcha code type must not be empty");
        }

        return switch (codeType.toLowerCase()) {
            case MATH_TYPE -> new MathGenerator(codeLength);
            case RANDOM_TYPE -> new RandomGenerator(codeLength);
            default -> throw new IllegalArgumentException("Invalid captcha generator type: " + codeType);
        };
    }

    /**
     * 验证码字体
     *
     * @return Font
     * @throws IllegalArgumentException 如果字体属性无效
     */
    @Bean
    public Font captchaFont() {
        if (captchaProperties == null || captchaProperties.getFont() == null) {
            throw new IllegalArgumentException("Captcha font properties must not be null");
        }

        CaptchaProperties.FontProperties fontProps = captchaProperties.getFont();
        if (!StringUtils.hasText(fontProps.getName())) {
            throw new IllegalArgumentException("Font name must not be empty");
        }

        int fontWeight = switch (fontProps.getWeight()) {
            case Font.PLAIN, Font.BOLD, Font.ITALIC -> fontProps.getWeight();
            default -> DEFAULT_FONT_WEIGHT;
        };
        return new Font(fontProps.getName(), fontWeight, fontProps.getSize());
    }
}